<?php
namespace app\admin\controller;
use app\model\Problem as ProblemModel;
use think\Db;

use app\lib\baidu\Api as baiduApi;


class Problem extends Base
{
    public function __construct(){
        $model = new ProblemModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;

        $categorys = $model->getCategoryList();
        $categorys = arrayParamExtractVal($categorys);

        $banks = Db::name('problem_bank')->select();
        $banks = arrayParamExtract($banks,'id','name');

        $fields = [
            'problem_bank_id'=>['name'=>'题库','type'=>'select1','params'=>$banks],
            'title'=>['name'=>'题目','type'=>'text','valids'=>['required']],
            'category'=>['name'=>'分类','type'=>'select1','params'=>$categorys],
        ];
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $categorys = $model->getCategoryList();
        $categorys = arrayParamExtractVal($categorys);

        $search_params = [
            [
                ['key'=>'category','name'=>'分类','type'=>'select1_1','params'=>$categorys],
                ['key'=>'title','name'=>'题目','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }


    public function index(){
        $ulogin = $this->login_user;
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'category','type'=>'='],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $this->assignSearchs();

        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            $list['data'][$k]['problem_bank_name'] = Db::name('problem_bank')->where('id',$vo['problem_bank_id'])->value('name');
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['title','category','problem_bank_id'],
                'nomust'=>[]
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }

        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['title','category','problem_bank_id'],
                'nomust'=>[]
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }

        return parent::updateData($id,$save_data);
    }

    public function export(){
        $model = $this->model;
        $list = $model->select();
        foreach ($list as $k => $vo) {
   
        }
        $data = [];
        $title = ['ID','标题','分类'];
        foreach ($list as $k => $vo) {
            $tmp = [
                $vo['id'],$vo['title'],$vo['category']
            ];
            $data[] = $tmp;
        }
        exportCsv(date('YmdHis'),$title,$data);
    }

//     public function aiCreate(){
//         set_time_limit ( 0 );
//         ini_set('memory_limit','-1');
//         ini_set('max_execution_time',0);

//         $vo = [
//             'api_param'=>'{"client_id":"2UdtilsxkinLDnwwvQUj1Dif","client_secret":"sU8i7ce6KBVBKFdjpBEveUFfcTNoHKcG"}',
//             'type'=>1,
//             'category'=>'数据库',
//             'knowledge'=>'yev2gy8pctwecqgj'
//         ];

//         $api = new baiduApi();
//         $api_param = json_decode($vo['api_param'],true);
//         $token = $api->token($api_param);
//         if (empty($token['access_token'])) {
//             return json(['code'=>5000,'msg'=>'token获取失败']);
//         }
//         $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro';

//         for ($i=0; $i < 100; $i++) { 
//             $result = $api->chat($api_url,$token['access_token'],[[
//                 'role'=>'user',
//                 'content'=>'请考我一个阿里云ACP认证数据库产品内容的题，随机一个多项选择题，提供标准答案，并附带解析，要求用json格式表达，参考"title":"题目内容","options":["选项1","选项2","选项3","选项4"],"answer":["A","B"], "analysis":"解析说明"'
//             ]],'你是一位阿里云考试的出题官');
//             dump($result);

//             if ($result['status'] == 0) {
//                 dump($result);die;
//             }


//             $content = str_replace(['```json','json```','```'], '', $result['answer']);
//             $content = str_replace("\n", "", $content); // 换行导致json无法解析
//             $content = json_decode($content,true);

//             // $answers = [];
//             // foreach ($content['answer'] as $answer) {
//             //     if (array_search($answer, $content['options']) !== false) {
//             //         $answers[] = array_search($answer, $content['options']);
//             //     }
//             // }

//             $answers = [];
//             foreach ($content['answer'] as $answer) {
//                 if (array_search($answer, ["A","B","C","D","E","F"]) !== false) {
//                     $answers[] = array_search($answer, ["A","B","C","D","E","F"]);
//                 }
//             }

//             if (empty($answers)) {
//                 return json(['code'=>5000,'msg'=>'无答案']);
//             }
//             sort($answers);
//             $save_data = [
//                 'title'=>$content['title'],
//                 'content'=>json_encode($content['options'],JSON_UNESCAPED_UNICODE),
//                 'analysis'=>$content['analysis'],
//                 'answer'=>implode(',', $answers),
//                 'type'=>$vo['type'],
//                 'category'=>$vo['category'],
//                 'ctime'=>date('Y-m-d H:i:s')
//             ]; 

//             Db::name('problem')->insert($save_data);
//         }
//         die;

//     }


    public function aiCreate(){
        ini_set('max_execution_time', 0);
        set_time_limit(0);

        while(true){
            $starttime = time();
            try{
                $rules = Db::name('problem_create')->where('status','in',[0,1])->order('type','asc')->select();
                if (empty($rules)) {
                    exit('empty rule');
                }

                $api = new baiduApi();
                $api_param = json_decode('{"client_id":"2UdtilsxkinLDnwwvQUj1Dif","client_secret":"sU8i7ce6KBVBKFdjpBEveUFfcTNoHKcG"}',true);
                $token = $api->token($api_param);
                if (empty($token['access_token'])) {
                    return json(['code'=>5000,'msg'=>'token获取失败']);
                }

                foreach ($rules as $rule) {
                    $max_num = $rule['type'] == 1 ? 30 : 80;
                    if ($rule['num'] >= $max_num) {
                        Db::name('problem_create')->where('id',$rule['id'])->update(['status'=>2]);
                        continue;
                    }
                    $knowledge = $rule['knowledge'];
                    $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/'.$knowledge.'/?access_token='.$token['access_token'];

                    $history = [];
                    $list = Db::name('problem_tmp')->where('create_id',$rule['id'])->select();
                    foreach ($list as $k => $vo) {
                        $content = $vo['content'];
                        if ($rule['mode'] > 0) {
                            $content = str_replace(['```json','json```','```'], '', $vo['content']);
                            $content = str_replace("\n", "", $content); // 换行导致json无法解析
                            $content = json_decode($content,true);
                            if ($rule['mode'] >= 1) {
                                unset($content['analysis']);
                            }
                            if ($rule['mode'] >= 2) {
                                unset($content['answer']);
                            }
                            if ($rule['mode'] >= 3) {
                                unset($content['options']);
                            }
                            $content = '```json
        '.json_encode($content,JSON_UNESCAPED_UNICODE).'
        ```';
                        }
           
                        $history[] = [
                            'role'=>'user',
                            'content'=>'1'
                        ];
                        $history[] = [
                            'role'=>'assistant',
                            'content'=>$content
                        ];
                    }
                    while ($rule['num'] < $max_num) {
                        $params = [
                            'query'=>'1',
                            'llm'=>[
                                'temperature'=>1,
                                'top_p'=>1,
                                'penalty_score'=>1
                            ],
                            'verbose'=>false,
                        ];
                        if (!empty($history)) {
                            $params['history'] = $history;
                        }
                        $result = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',['Content-Type: application/json']);
                        // dump($api_url);
                        // dump(json_encode($params,JSON_UNESCAPED_UNICODE));
                        // dump($result);die;
                        $result = json_decode($result,true);
                        if (!empty($result['error_code'])) {
                            if (strpos($result['error_msg'], '336103') !== false) {
                                Db::name('problem_create')->where('id',$rule['id'])->update(['mode'=>$rule['mode']+1]);
                                throw new \Exception("next"); 
                            }
                            return json(['code'=>5000,'msg'=>$result['error_msg']]);
                        }

                        $content = $history[count($history)-1]['content'];
                        if ($rule['mode'] > 0) {
                            $content = str_replace(['```json','json```','```'], '', $vo['content']);
                            $content = str_replace("\n", "", $content); // 换行导致json无法解析
                            $content = json_decode($content,true);
                            if ($rule['mode'] >= 1) {
                                unset($content['analysis']);
                            }
                            if ($rule['mode'] >= 2) {
                                unset($content['answer']);
                            }
                            if ($rule['mode'] >= 3) {
                                unset($content['options']);
                            }
                            $content = '```json
        '.json_encode($content,JSON_UNESCAPED_UNICODE).'
        ```';
                            $history[count($history)-1]['content'] = $content;
                        }

                        $history[] = [
                            'role'=>'user',
                            'content'=>'1'
                        ];
                        $history[] = [
                            'role'=>'assistant',
                            'content'=>$result['result']
                        ];

                        Db::name('problem_tmp')->insert(['content'=>$result['result'],'create_id'=>$rule['id'],'mode'=>$rule['mode']]);
                        Db::name('problem_create')->where('id',$rule['id'])->inc('num')->update();
                        $rule['num']++;
                    }
                }
            } catch (\Exception $e) {
                sleep(5);
                continue;
            }
            sleep(5);
        }

    }

    public function tmpSwitch(){
        $rules = Db::name('problem_create')->where([
            ['problem_bank_id','>',0],
            ['type','=',1]
        ])->select();
        $answers = ['A','B','C','D','E','F','G'];
        foreach ($rules as $rule) {
            $list = Db::name('problem_tmp')->where([
                ['create_id','=',$rule['id']],
                ['status','=',0]
            ])->select();
            
            foreach ($list as $k => $vo) {
                $content = str_replace(['```json','json```','```'], '', $vo['content']);
                $content = str_replace("\n", "", $content); // 换行导致json无法解析
                $content = json_decode($content,true);

                Db::name('problem_tmp')->where('id',$vo['id'])->update(['status'=>1]);
                if (empty($content)) {
                    continue;
                }
                $save_data = [
                    'problem_bank_id'=>$rule['problem_bank_id'],
                    'title'=>$content['title'],
                    'content'=>json_encode($content['options'],JSON_UNESCAPED_UNICODE),
                    'type'=>$rule['type'],
                    'category'=>$rule['category'],
                    'analysis'=>$content['analysis'],
                    'answer'=>[],
                    'ctime'=>date('y-m-d H:i:s')
                ];
                if ($rule['type'] == 1) {
                    foreach ($content['answer'] as $answer) {
                        if (array_search($answer, $answers) !== false) {
                            $save_data['answer'][] = array_search($answer, $answers);
                        }
                    }
                }else{
                    $save_data['answer'][] = array_search($content['answer'], $answers);
                }
                
                
                if (empty($save_data['answer'])) {
                    continue;
                }
                $save_data['answer'] = implode(',',$save_data['answer']);
                Db::name('problem')->insert($save_data);
            }
        }
    }


    public function import(){
        set_time_limit ( 0 );
        ini_set('memory_limit','10240M');

        if (request()->isPost()) {
            $fields = [
                'must'=>['problem_bank_id'],
            ];
            $params = paramFilter(request()->param(),$fields);
            if (!empty($params['error_msg'])) {
                $this->error($params['error_msg']);
            }

            $file = $_FILES['file'];
            if (empty($file)) {
                $this->error('未检测到文件');
            }

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
            $list=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式
            array_shift($list);  //删除第一个数组(标题);

            $results = [];
            $answers = ['A','B','C','D','E','F','G'];
            $save_datas = [];
            foreach ($list as $k => $vo) {
                $save_data = [
                    'problem_bank_id'=>$params['problem_bank_id'],
                    'title'=>$vo[1],
                    'content'=>json_encode(explode(';',$vo[2]),JSON_UNESCAPED_UNICODE),
                    'type'=>$vo[0] == '单选' ? 0 : 1,
                    'category'=>str_replace(['《','》'], '', $vo[4])
                ];
                if ($save_data['type'] == 0) {
                    $save_data['answer'] = array_search($vo[3], $answers);
                }else{
                    foreach (explode(',',$vo[3]) as $answer) {
                        if (array_search($answer, $answers) !== false) {
                            $save_data['answer'][] = array_search($answer, $answers);
                        }
                    }
                    $save_data['answer'] = implode(',',$save_data['answer']);
                }
                $save_datas[] = $save_data;
            }

            if ( Db::name('problem')->insertAll($save_datas) ) {
                $this->success('导入成功');
            }else{
                $this->error('导入失败，请检查文件重试');
            }
          
        }

        $banks = Db::name('problem_bank')->select();
        $banks = arrayParamExtract($banks,'id','name');
        return view('import', [
            'banks'=>$banks
        ]);
    }


   
}
